<?php

declare(strict_types=1);

/**
 * Author: Jesse
 * Email : jessedev@163.com
 * Date: 2024/6/17 00:38
 * FileName: AppendRequestIdProcessor.php
 * DESC: The Relentless Pursuit of Perfection.
 */

namespace Common\Kernel\Log;

use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;

/**
 * 将同一个请求的日志关联起来
 */
class AppendRequestIdProcessor implements ProcessorInterface
{
    /**
     * 请求ID
     */
    public const REQUEST_ID = 'log.request.id';

    /**
     * @param array|LogRecord $record
     * @return array|LogRecord
     */
    public function __invoke(array|LogRecord $record): array|LogRecord
    {
        $record['extra']['req_id'] = Context::getOrSet(self::REQUEST_ID, uniqid());
        $record['extra']['coroutine_id'] = Coroutine::id();

        return $record;
    }
}